<?php

/**
 * 用户余额/积分
 * Created by PhpStorm.
 * User: lirui
 * Date: 2020/2/07
 * Time: 下午8:42
 */

namespace App\Http\Controllers\Api;

use App\Models\CashApply;
use App\Models\CreditLog;
use App\Models\Order;
use App\Services\BalanceService;
use App\Services\CashApplyService;
use App\Services\ConfigService;
use App\Services\PayService;
use Illuminate\Support\Facades\DB;

/**
 * 余额
 * Class CreditController
 * @package App\Http\Controllers\Api
 */
class CreditController extends Controller
{
    /**
     * 获取用户余额账单
     */
    public function bill()
    {
        $pm = request()->input('pm');
        $builder = CreditLog::whereUid($this->uid);

        if ($pm == 1) {
            $builder->where('num', '>', 0);
        }
        if ($pm == 2) {
            $builder->where('num', '<', 0);
        }
        if ($pm == 3) {
            $builder->where('log_type', 24);
        }

        $list = $builder->orderBy('id', 'desc')->paginate(10);

        return $this->success($list);
    }

    /**
     * 用户充值余额
     * @throws \Throwable
     */
    public function rechargeBalance()
    {
        DB::beginTransaction();

        $money = (float)request()->input('money');
        $payType = request()->input('payType');
        if(empty($payType)){
            $payType = 'weixin';
        }
        $config = ConfigService::getSysValueByType(13);

        $balanceConfig = $config['balance'];

        if (!$balanceConfig['recharge']) {
            return $this->error(-1, '系统暂未开启线上充值');
        }
        if ($money <= 0) {
            return $this->error(-1, '充值金额错误！');
        }
        if ($balanceConfig['min_recharge'] && $money < $balanceConfig['min_recharge']) {
            return $this->error(-1, "最小充值{$balanceConfig['min_recharge']}元");
        }

        $order = BalanceService::createRechargeOrder($this->userInfo, $money);

        if (is_error($order)) {
            DB::rollBack();
            return $this->error(-1, $order['message']);
        }

        $orderId = $order['order_id'];

        if ($orderId ) {
            try {
                $orderInfo = Order::getByOrderId($orderId);
                if (!$orderInfo) {
                    DB::rollBack();
                    return $this->error(-1, '支付订单不存在!');
                }
                if ($orderInfo['paid']) {
                    DB::rollBack();
                    return $this->error(-1, '订单已支付!');
                }
                $payData = array(
                    'body' => '余额充值',
                    'subject' => '余额充值',
                    'payType' => $payType,
                    'orderId' => $orderId,
                    'pay_price' => $order['pay_price'],
                    'payAttach' => 'recharge_balance',
                );

                //统一支付中间方法
                $data = (new PayService())->pay($payData);

                if(isset($data['errorCode']) && $data['errorCode'] == -1 ){
                    return $this->error('-1',$data['message']);
                }
                DB::commit();
                return $this->success($data, '订单创建成功');

            } catch (\Exception $e) {
                DB::rollBack();
                return $this->error(-1, $e->getMessage());
            }
        } else {
            DB::rollBack();
            return $this->error(-1, '订单生成失败2!');
        }
    }

    /**
     * 用户余额提现申请
     * @throws \Throwable
     */
    public function extractBalance()
    {
        DB::beginTransaction();

        $extractType = request()->input('extract_type');//提现方式
        $cashType = request()->input('cash_type', 'yue');//提现种类
        if(!$cashType){
            $cashType = 'yue';
        }
        $money = request()->input('money');
        $config = ConfigService::getSysValueByType(13);
        $configBalance = $config['balance'];
        $name = trim(request()->input('name'));

        $exists = CashApply::whereUid($this->uid)->whereCategory(2)->whereStatus(0)->first();

        if ($exists) {
            return $this->error(-1, "提现申请审核中，请勿重复提交");
        }

        //参数判断
        //$commission = max(0, $configBalance['withdraw_commission']);

        if ($configBalance['withdraw_limit'] > 0
            && $money < $configBalance['withdraw_limit']
        ) {
            return $this->error(-1, "最低提现{$configBalance['withdraw_limit']}元");
        }
        if($cashType == 'yue'){          //余额提现
            if ($this->userInfo['balance'] < $money) {
                return $this->error(-1, "余额不足");
            }
        }
        if ($configBalance['withdraw_commission'] > 0) {
            $commission = $money * ($configBalance['withdraw_commission'] / 100);
        }else{
            $commission = 0.01;
        }

        //是否手续费在免额区间
        if ($configBalance['withdraw_commission_free_max'] > 0
            && $money >= $configBalance['withdraw_commission_free_min']
            && $money <= $configBalance['withdraw_commission_free_max']
        ) {
            $commission = 0;
        }

        if ($money <= 0) {
            return $this->error(-1, "提现金额错误");
        }

        $model = new CashApply();
        $model->cash_type = $cashType;
        $model->order_ids = '';
        $model->order_no = '';
        $model->type = $extractType;
        $model->category = 2;
        $model->commission = $commission;
        $model->uid = $this->uid;
        $model->openid = $this->userInfo['wxapp_openid'];
        $model->balance = $money;

        if(empty(request()->input('real_name'))){
            return $this->error(-1, "请输入真实姓名");
        }
        if(empty(request()->input('phone'))){
            return $this->error(-1, "手机号不能为空！");
        }
        //新加字段
        $model->real_name = request()->input('real_name');
        $model->phone = request()->input('phone');


        //表单判断
        if ($extractType == 'bank') {
            $cardnum = trim(request()->input('cardnum'));
            $bankaddress = trim(request()->input('bankaddress'));
            $bankname = trim(request()->input('bankname'));
            if (!$name) {
                return $this->error(-1, "请填写持卡人姓名");
            }
            if (!$cardnum) {
                return $this->error(-1, "请填写银行卡号");
            }
            if (!$bankname) {
                return $this->error(-1, "请选择银行");
            }
            $model->name = $name;
            $model->cardnum = $cardnum;
            $model->bankname = $bankname;
            $model->bank_address = $bankaddress;
        } else if ($extractType == 'weixin') {
            $weixin = trim(request()->input('weixin'));
            if (!$weixin) {
                return $this->error(-1, "请填写微信号");
            }
            $model->weixin = $weixin;
        } else if ($extractType == 'alipay') {
            $alipayCode = trim(request()->input('alipay_code'));
            if (!$alipayCode) {
                return $this->error(-1, "请填写支付宝账号");
            }
            $model->alipay_code = $alipayCode;
        }

        $ret = $model->saveOrFail();

        if ($ret) {
            CashApplyService::extractBalanceSuccess($model);

            DB::commit();
            return $this->success('', '申请成功');
        } else {
            DB::rollBack();
            return $this->error(-1, "申请失败，系统错误");
        }
    }
}
